
import { LoginParams, Response } from '../types/common'
import { request } from '../utils/request'
import { API_URLS } from '../config'
import { ElMessage } from 'element-plus'
import type { Menu } from '../types/menu'

export const login = async (params: LoginParams): Promise<boolean> => {
  const response:Response<string> = await request(API_URLS.LOGIN, {
    method: 'POST',
    body: JSON.stringify(params)
  })

  if (response.code === 200) {
      localStorage.setItem('token', response.data)
      if (params.rememberMe) {
        localStorage.setItem('username', params.username)
      } else {
        localStorage.removeItem('username')
      }
      ElMessage.success('登录成功')
      return true
    }

  return false
}

export const logout = async (): Promise<boolean> => {

  // 调用退出登录接口
  const response:Response<boolean> =  await request(API_URLS.LOGOUT, {method: 'GET'})

  if (response.code === 200) {
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    // 显示退出成功消息
    ElMessage.success('退出登录成功')
  }

  // 只要点击退出登录，就返回true(跳转到登录页)
  return true
}

export const getPermissions = async (): Promise<Menu[]> => {
  const response:Response<Menu[]> = await request(API_URLS.PERMISSIONS, { method: 'GET' })

  if (response.code === 200) {
    localStorage.setItem('permissions', JSON.stringify(response.data))
    console.log('查询用户权限成功')
    return response.data
  }
  return []
}
